﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;

namespace MediaController.Subs.Provider
{
    public class TitlesFolderInfo : IEnumerable
    {
        private readonly string _folderPath;

        public string FolderPath
        {
            get { return _folderPath; }
        }

        public TitleFileInfo[] MediaFileInfos { get; private set; }

        public TitlesFolderInfo(string folderPath, SearchOption searchOption = SearchOption.AllDirectories)
        {
            if (folderPath == null) throw new ArgumentNullException("folderPath");
            if (!Directory.Exists(folderPath)) throw new DirectoryNotFoundException(string.Format("Couldnt find directory [{0}]", folderPath));

            _folderPath = folderPath;
            ScanFolder(folderPath, searchOption);
        }

        private void ScanFolder(string folderPath, SearchOption searchOption)
        {
            var titles = new List<TitleFileInfo>();

            foreach (FileInfo fileInfo in new DirectoryInfo(folderPath).GetFiles("*.*", searchOption))
            {
                if (Regex.Match(fileInfo.FullName, @"^.*\.mkv$|^*.avi|^*.wmv", RegexOptions.IgnoreCase).Success)
                {
                    if (/*fileInfo.Length > 100000000 &&*/ fileInfo.Directory != null)
                    {
                        var titleFileInfo = new TitleFileInfo(fileInfo.FullName);
                        var hasSubs = fileInfo.Directory.GetFiles(Path.GetFileNameWithoutExtension(fileInfo.Name) + ".srt").Length > 0 ;
                        if (hasSubs)
                        {
                            titleFileInfo.HasSubs = true;
                        }
                        titles.Add(titleFileInfo);
                    }
                }
            }

            MediaFileInfos = titles.ToArray();
        }

        public IEnumerator GetEnumerator()
        {
            return MediaFileInfos.GetEnumerator();
        }
    }
}